<?php

namespace Formax;

class AJAX extends \Phalcon\DI\Injectable
{

    /**
     * 通用错误代码定义
     */
    const SUCCEED         = 200; // 响应成功
    const AUTH_FAILED     = 401; // 无权限
    const FORBIDDEN       = 403; // 禁止访问
    const INVALID_REQUEST = 404; // 无效请求
    const INTERNAL_ERROR  = 500; // 内部错误

    /**
     * AJAX 响应数据 (JSON格式)
     *
     * @param  integer $code    响应代码
     * @param  string  $message 响应消息
     * @param  array   $data    响应数据
     * @return string
     */
    public function response($code, $message = null, array $data = null)
    {
        return $this->response
            ->setContentType('application/json', 'utf-8') // set http response header
            ->setJsonContent(array(
                'code'      => (int) $code,
                'message'   => $message,
                'data'      => $data,
                'timestamp' => time(),
            ), defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE : null);
    }

    /**
     * 响应错误信息
     *
     * @param  string $message
     * @param  array  $data
     * @return string
     */
    public function error($message = null, array $data = null)
    {
        return $this->response(AJAX::INTERNAL_ERROR, $message, $data);
    }

    /**
     * 响应成功信息
     *
     * @param  string $message
     * @param  array  $data
     * @return string
     */
    public function success($message = null, array $data = null)
    {
        return $this->response(AJAX::SUCCEED, $message, $data);
    }
}
